import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer1 {
    public ServerSocket serverSocket=null;
    public TcpEchoServer1(int port) throws IOException {
        serverSocket=new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器状态状态正常");
        //直接创建线程池来执行通信过程
        ExecutorService service= Executors.newCachedThreadPool();
        while(true){
            Socket socket=serverSocket.accept();
            service.submit(()->{
                processConnect(socket);
            });
        }
    }
    //处理与每位用户的请求
    public void processConnect(Socket socket){
        System.out.printf("[%s:%d]   客户端上线！\n",socket.getInetAddress(),socket.getPort());
        try(InputStream inputStream=socket.getInputStream();
            OutputStream outputStream=socket.getOutputStream()){
            Scanner scanner=new Scanner(inputStream);
            PrintWriter writer=new PrintWriter(outputStream);
            while(true){
                if(!scanner.hasNext()){
                    System.out.printf("[%s:%d]   客户端下线！\n",socket.getInetAddress(),socket.getPort());
                    break;
                }
                String request=scanner.next();
                String response=procsee(request);
                writer.println(response);
                writer.flush();
                System.out.printf("[%s:%d]     请求：%s     响应：%s\n",socket.getInetAddress(),socket.getPort(),request,response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public String procsee(String s){
        return s;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer1 server1=new TcpEchoServer1(8776);
        server1.start();
    }
}
